import type { RouteRecordRaw } from 'vue-router'
import { LoginRequest } from '@/api/system/login.request'
import { generateRoutes } from '@/router/router.helper'
import { STATIC_ROUTE_LIST } from '@/router/router.database'

export default defineStore('permission', () => {
  /** 后端数据解析后的动态路由表 */
  const dynamicRouteList = ref<RouteRecordRaw[]>([])

  /** 递归路由表 用于无限递归菜单 */
  const routeList = shallowRef<RouteRecordRaw[]>([])

  /** 根据角色生成可访问的 Routes（可访问路由 = 常驻路由 + 有访问权限的动态路由） */
  async function getRoutes() {
    try {
      // 获取后端菜单数据 并对其进行扁平化处理
      const backRouteList = await LoginRequest.getRoutes()
      dynamicRouteList.value = generateRoutes(backRouteList)
      routeList.value = [...STATIC_ROUTE_LIST, ...dynamicRouteList.value]
    } catch (error) {
      return Promise.reject(error)
    }
  }

  return { routeList, dynamicRouteList, getRoutes }
})
